<template>
	<div class="textbook_box">
		<el-form :model="editForm" :rules="rules" :inline="true" ref="editForm" v-show="from == 'admin'">
			<el-row>
				<el-col :span="5">
					<el-form-item label="教材名称" prop="textbookName">
						<el-input placeholder="请输入教材名称" v-model="editForm.textbookName" maxlength="255"
							style="width:100%" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="专业" prop="majorId">
						<el-select v-model="editForm.majorId" placeholder="请选择专业" style="width:100%">
							<el-option v-for="item in majors" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="版本号" prop="version">
						<el-input placeholder="请输入版本号" v-model="editForm.version" maxlength="255" style="width:100%"
							clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="状态" prop="state">
						<el-select v-model="editForm.state" placeholder="请选择状态" style="width:100%">
							<el-option v-for="item in states" :key="item.value" :label="item.label" :value="item.value">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-button @click='toInfo'>预览教材</el-button>
					<el-button type="primary" @click="editData" :disabled='dataloading'>保存教材</el-button>
				</el-col>
			</el-row>
		</el-form>
		<el-form :model="editForm" ref="editForm" :inline="true" v-show="from == 'teacher'">
			<el-row>
				<el-col :span="4">
					<el-form-item label="教材名称：" prop="textbookName">
						<div class="text-ellipsis">{{ editForm.textbookName }}</div>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="专业：" prop="majorId">
						<div class="text-ellipsis"><span v-for="item in majors" v-if="item.id == editForm.majorId">{{
							item.name }}</span></div>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="版本号：" prop="version">
						<div class="text-ellipsis">{{ editForm.version }}</div>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="状态：" prop="state">
						<div class="text-ellipsis"><span v-for="item in states" v-if="item.value == editForm.state">{{
							item.label }}</span></div>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-form-item label="创建人：" prop="createUserName">
						<div class="text-ellipsis">{{ editForm.createUserName }}</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<div class="textbook_new_tree">
			<div class="textbook_new_tree_head">
				<span> 教材目录<span v-show="from == 'admin'">（{{ treeNum }}章）</span></span>
				<div class="textbook_new_tree_head_right" v-show="from == 'admin'" @click='openAddChapter'>
					<i class="el-icon-plus"></i>
				</div>
			</div>
			<div class="textbook_new_tree_body">
				<div class="textbook_new_tree_body_search">
					<el-input v-model="chapterName" size="small" placeholder="请输入章名称搜索"
						style='width: calc(100% - 75px);' clearable />
					<div class="data_btn r add" @click='getTreeList'>
						<i class="el-icon-search" />搜索
					</div>
				</div>
				<div class="textbook_new_tree_body_list beautifulScroll">
					<div class="textbook_new_tree_body_empty" v-if="treeList.length == 0">
						<div class="textbook_new_tree_body_emptycont">
							<img src="@/assets/images/textbook_new_tree_body_emptycont.png" alt="">
							<div>暂无教材章节~</div>
							<div v-show="from == 'admin'" style="margin: 20px  0 0 0 ;">
								<el-button @click='openAddChapter'><i class="el-icon-plus"></i>点击添加章节</el-button>
							</div>
						</div>
					</div>
					<div class="data_card_list" v-for="chapter in treeList">
						<div class="chapter_text">
							<div class="chapter_text_in">
								<div class="chapter_text_all text-ellipsis" @click.stop="changeOpen(chapter)">
									<span class="chapter_text_allicon">
										<i class="el-icon-arrow-right "
											v-show="!openChapters.includes(chapter.textbookChapterId)"></i>
										<i class="el-icon-arrow-down "
											v-show="openChapters.includes(chapter.textbookChapterId)"></i>
									</span>
									<span class="chapter_text_span">
										<i class="el-icon-folder-opened" />
									</span>
									<div class="text-ellipsis pointer " v-if="chapter.pieceName">
										{{ chapter.pieceName }}
									</div>
									<div class="text-ellipsis pointer">
										{{ chapter.chapterName }}
									</div>
								</div>
							</div>
							<div class="arco_tree_btns" v-show="from == 'admin'">
								<div class="arco_tree_btn" @click.stop="openEditChapter(chapter)">
									<i class="el-icon-edit" />
								</div>
								<div class="arco_tree_btn" @click.stop="openDeleteChapter(chapter)">
									<i class="el-icon-delete" />
								</div>
								<div class="arco_tree_btn" @click.stop="openAddSection(chapter)">
									<i class="el-icon-plus" />
								</div>
							</div>
						</div>
						<div class="section_text_all" v-show="openChapters.includes(chapter.textbookChapterId)"
							v-if="chapter.sectionDirectoryDtos && chapter.sectionDirectoryDtos.length">
							<div class="section_text" v-for="section in chapter.sectionDirectoryDtos"
								:class="from + ' ' + (openInfo.chapterSectionId == section.chapterSectionId ? 'active' : '')">
								<span class="chapter_text_allicon">
									<i class="el-icon-collection-tag" />
								</span>
								<div class="section_text_in">
									<div class="chapter_text_all text-ellipsis"
										@click.stop="openInfoSection(chapter, section)">
										{{ section.sectionName }}
									</div>
								</div>
								<div class="arco_tree_btns" v-show="from == 'admin'">
									<div class="arco_tree_btn" @click.stop="openEditSection(section)">
										<i class="el-icon-edit" />
									</div>
									<div class="arco_tree_btn" @click.stop="openDeleteSection(section)">
										<i class="el-icon-delete" />
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="textbook_new_cont">
			<div class="textbook_new_cont_body_cover" v-show="aicreateing">
				<div class="textbook_new_cont_body_coverin">
					<img src="@/assets/images/textbook_new_cont_body_coverin.png" alt=""><span
						class="fl">内容生成中，请稍等</span>
					<div class="momentum"></div>
				</div>
			</div>
			<div class="textbook_new_tree_head">
				详情：{{ openInfo.sectionName || '-' }}
				<el-button @click='openAddContent(newPage, 0)' type='primary' :disabled="!openInfo.chapterSectionId"
					size='mini' class='textbook_btn' v-show="!openList || openList.length <= 0"
					style='margin-left: 15px;'>添加内容</el-button>
				<el-button @click='addDataContent(2)' type='primary' :loading="loading" size='mini'
					class='textbook_btn' v-show="sectionEdited" style='margin-left: 15px;'>保存本节</el-button>
				<div @click='openAIcontent' class="textbook_btn_ai like_btn" v-show="!aicreate"
					:class="{ 'disabled': !openInfo.chapterSectionId }">
					<img src="@/assets/images/textbook_btn_ai.png" alt=""> AI添加
				</div>
				<div @click='closeAIcontent' class="textbook_btn_ai like_btn" v-show="aicreate"
					:class="{ 'disabled': !openInfo.chapterSectionId }">
					<img src="@/assets/images/textbook_btn_ai.png" alt=""> 取消AI添加
				</div>
			</div>
			<div class="textbook_new_cont_body">
				<div class="textbook_new_tree_body_back" v-show="!openInfo.chapterSectionId">
					<img src="@/assets/images/textbook_new_tree_body.png" class="textbook_new_tree_body_back">
					<div class="textbook_new_tree_body_backinfo">
						<div>查看<span>AI智能添加教材</span>需要先选择左侧课程小节</div>
						<div class="textbook_new_tree_body_backinfo1">
							<img src="@/assets/images/textbook_new_tree_body_backinfo1.png"
								class="textbook_new_tree_body_back">
							<img src="@/assets/images/textbook_new_tree_body_backinfo21.png"
								class="textbook_new_tree_body_backinfo2">
							<img src="@/assets/images/textbook_new_tree_body_backinfo22.png"
								class="textbook_new_tree_body_backinfo2">
						</div>
					</div>
				</div>
				<div class="textbook_new_tree_body_left" v-show="aicreate && !aihtml">
					<img src="@/assets/images/textbook_new_tree_body_left.png" class="textbook_new_tree_body_back">
					<div class="textbook_new_tree_body_left1">
						<img src="@/assets/images/textbook_new_tree_body_left11.png">
						<img src="@/assets/images/textbook_new_tree_body_left12.png"
							class="textbook_new_tree_body_left12">
					</div>
					<div class="textbook_new_tree_body_left4">
						<div class="textbook_new_tree_body_left5">
							<div class="textbook_new_tree_body_left51">
								<img src="@/assets/images/textbook_new_tree_body_left511.png" alt="">
								内容框架
							</div>
							<textarea resize="none" placeholder="请输入内容框架" class="textbook_new_tree_body_left52"
								v-model="aiForm.contentRefer"></textarea>
						</div>
						<div class="textbook_new_tree_body_left5">
							<div class="textbook_new_tree_body_left51">
								<img src="@/assets/images/textbook_new_tree_body_left511.png" alt="">
								核心知识点
							</div>
							<textarea resize="none" placeholder="请输入核心知识点" class="textbook_new_tree_body_left52"
								v-model="aiForm.knowledge"></textarea>
						</div>
					</div>
					<div class="textbook_new_tree_body_left2">
						<div class="textbook_new_tree_body_left3  like_btn" :class="{ 'disabled': aicreateing }"
							@click="startAiCreate">
							{{ aicreateing ? '正在生成' : '开始生成' }}
						</div>
					</div>
				</div>
				<div class="textbook_new_tree_body_left edit" :class="'state' + rightstate" v-show="aicreate && aihtml">
					<img src="@/assets/images/textbook_new_tree_body_left.png" class="textbook_new_tree_body_back">
					<div class="textbook_new_tree_body_left1">
						<img src="@/assets/images/textbook_new_tree_body_left11.png">
						<img src="@/assets/images/textbook_new_tree_body_left12.png"
							class="textbook_new_tree_body_left12">
					</div>
					<div class="textbook_new_tree_body_left8">
						<div class="textbook_new_tree_body_btn " @click="openLeft">
							<i class="el-icon-d-arrow-right" v-if="rightstate != 1"></i><i class="el-icon-d-arrow-left"
								v-if="rightstate == 1"></i>{{ rightstate == 1 ? '收起' : '展开' }}
						</div>
					</div>
					<div class="textbook_new_tree_body_left6 beautifulScroll" v-html="aihtml">
					</div>
					<div class="textbook_new_tree_body_left7">
						<div class="textbook_new_tree_body_btn " @click.stop="reStartAiCreate">
							<i class="el-icon-refresh"></i>重新生成
						</div>
						<div class="textbook_new_tree_body_btn " @click.stop="editAiCreate">
							<i class="el-icon-edit-outline"></i>编辑
						</div>
						<div class="textbook_new_tree_body_btn " @click.stop="addToSectionBefore">
							<i class="el-icon-copy-document"></i>一键应用
						</div>
					</div>
				</div>
				<div class="textbook_new_tree_body_right" :class="'state' + rightstate"
					v-show="openInfo.chapterSectionId">
					<div class="textbook_new_tree_body_right_btn" v-show="aicreate && aihtml && openList.length">
						<div class="textbook_new_tree_body_btn " @click="openRight">
							<i class="el-icon-d-arrow-left" v-if="rightstate != 3"></i><i class="el-icon-d-arrow-right"
								v-if="rightstate == 3"></i>{{ rightstate == 3 ? '收起' : '展开' }}
						</div>
					</div>
					<div class="textbook_page" v-for='(content, index) in openList' :key="content.sectionContentId">
						<div class="textbook_pagecont">
							<editor-more :content='content.contentHtml'
								@change="((data) => { contentChange(data, index) })"></editor-more>
						</div>
						<div class="textbook_pagenum">第{{ content.page }}页</div>
						<div class="textbook_pagebtn">
							<el-button type="danger" size="small"
								@click.stop="openDeleteContent(content.page, index)">删除本页</el-button>
							<el-button type="primary" size="small"
								@click.stop="openAddContent(content.page * 1 + 1, index + 1)">添加分页</el-button>
						</div>
					</div>
				</div>
				<div class="textbook_new_tree_body_back edit" v-if="adeditshow">
					<img src="@/assets/images/textbook_new_tree_body.png" class="textbook_new_tree_body_back">
					<div class="textbook_new_tree_body_left1">
						<img src="@/assets/images/textbook_new_tree_body_left11.png">
						<img src="@/assets/images/textbook_new_tree_body_left12.png"
							class="textbook_new_tree_body_left12">
						<div class="textbook_new_tree_body_btn " @click.stop="editCloseAiCreate"
							style="margin: 0 15px;">
							<i class="el-icon-back"></i>返回
						</div>
					</div>
					<div class="adedit_head">
						<img src="@/assets/images/adedit_head.png" alt="">
					</div>
					<div class="textbook_new_tree_body_left8">
						<div class="textbook_new_tree_body_btn " @click="checkAiCreate">
							<i class="el-icon-document-checked"></i>保存并应用
						</div>
					</div>
					<div class="textbook_new_edit_ai">
						<editor-more :content='aiedithtml' :height="520" @change="contentChangeAi"></editor-more>
					</div>
				</div>
			</div>
		</div>
		<el-dialog title="添加章" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true'
			:visible.sync="chapterAddDialog" width="500px">
			<el-form :model="chapterAddForm" :rules="rules" ref="chapterAddForm" label-width="90px"
				style='width: calc(100% - 30px);'>
				<el-form-item label="章名称" prop="chapterName">
					<el-input placeholder="请输入章名称" v-model="chapterAddForm.chapterName" maxlength="255"
						@keyup.enter.native="addDataChapter" clearable></el-input>
				</el-form-item>
				<el-form-item label="篇名" prop="pieceName">
					<el-input placeholder="请输入篇名" v-model="chapterAddForm.pieceName" maxlength="255"
						clearable></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetAddChapter">取 消</el-button>
				<el-button type="primary" @click="addDataChapter" :disabled='dataloading'>确 定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="编辑章" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true'
			:visible.sync="chapterEditDialog" width="500px">
			<el-form :model="chapterEditForm" :rules="rules" ref="chapterEditForm" label-width="90px"
				style='width: calc(100% - 30px);'>
				<el-form-item label="章名称" prop="chapterName">
					<el-input placeholder="请输入章名称" v-model="chapterEditForm.chapterName" maxlength="255"
						@keyup.enter.native="editDataChapter" clearable></el-input>
				</el-form-item>
				<el-form-item label="篇名" prop="pieceName">
					<el-input placeholder="请输入篇名" v-model="chapterEditForm.pieceName" maxlength="255"
						clearable></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetEditChapter">取 消</el-button>
				<el-button type="primary" @click="editDataChapter" :disabled='dataloading'>确 定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="添加小节" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true'
			:visible.sync="sectionAddDialog" width="500px">
			<el-form :model="sectionAddForm" :rules="rules" ref="sectionAddForm" label-width="90px"
				style='width: calc(100% - 30px);'>
				<el-form-item label="小节名称" prop="sectionName">
					<el-input placeholder="请输入小节名称" v-model="sectionAddForm.sectionName" maxlength="255"
						@keyup.enter.native="addDataSection" clearable></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetAddSection">取 消</el-button>
				<el-button type="primary" @click="addDataSection" :disabled='dataloading'>确 定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="编辑小节" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true'
			:visible.sync="sectionEditDialog" width="500px">
			<el-form :model="sectionEditForm" :rules="rules" ref="sectionEditForm" label-width="90px"
				style='width: calc(100% - 30px);'>
				<el-form-item label="小节名称" prop="sectionName">
					<el-input placeholder="请输入小节名称" v-model="sectionEditForm.sectionName" maxlength="255"
						@keyup.enter.native="editDataSection" clearable></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetEditSection">取 消</el-button>
				<el-button type="primary" @click="editDataSection" :disabled='dataloading'>确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
import EditorMore from "@/components/Editor/index.vue";
import { putProgress } from "@/utils/oss.js";
import { majorList } from '@/api/major.js'
import { selectTextbookDetail, selectTextbookChapterCount, selectTextbookDirectory, selectTextbookDirectoryByUserId, updateTextbook, saveTextbookChapter, updateTextbookChapter, removeTextbookChapter, saveTextbookChapterSection, updateTextbookChapterSection, removeTextbookChapterSection, saveTextbookChapterSectionContent, updateTextbookChapterSectionContent, removeTextbookChapterSectionContent, selectTextbookContentList, saveBatchTextbookSectionContent, generateTextbookSectionContent } from "@/api/textbook.js"
export default {
	components: {
		EditorMore
	},
	data() {
		var checkNumber = (rule, value, callback) => {
			if (!value) {
				return callback(new Error('请填写数字'));
			} else if (isNaN(Number(value))) {
				return callback(new Error('请填写数字'));
			} else if (!Number.isInteger(Number(value))) {
				return callback(new Error('请输入整数'));
			} else {
				return callback();
			}
		};
		return {
			aicreate: false,
			aicreateing: false,
			rightstate: 2,
			aihtml: '',
			aiedithtml: '',
			adeditshow: false,
			aiForm: {
				contentRefer: '',
				knowledge: '',
			},
			chapterName: '',
			openInfo: {
				textbookChapterId: '',
				chapterName: '',
				pieceName: '',
				chapterSectionId: '',
				sectionName: '',
				beforeSectionId: '',
			},
			sectionEdited: false,
			sectionEditIndex: 0,
			loading: false,
			newPage: 1,
			openList: [],
			sectionIds: [],
			openChapters: [],
			treeList: [],
			treeNum: 0,
			dataloading: false,
			textbookId: this.$route.query.textbookId,
			from: this.$route.query.from,
			majors: [],
			states: [{
				value: 1,
				label: "启用"
			}, {
				value: 2,
				label: "禁用"
			}],
			chapterAddDialog: false,
			chapterEditDialog: false,
			chapterAddForm: {
				chapterName: '',
				pieceName: '',
			},
			chapterEditForm: {
				chapterName: '',
				pieceName: '',
			},
			sectionAddDialog: false,
			sectionEditDialog: false,
			sectionAddForm: {
				sectionName: '',
				textbookChapterId: '',
			},
			sectionEditForm: {
				sectionName: '',
			},
			editForm: {
				textbookId: '',
				textbookName: '',
				majorId: '',
				version: '',
				state: '',
				prefaceHtml: '',
				textbookCover: '',
			},
			rules: {
				contentRefer: [{
					required: true,
					message: '请输入内容框架',
					trigger: 'blur'
				}],
				knowledge: [{
					required: true,
					message: '请输入核心知识点',
					trigger: 'blur'
				}],
				textbookName: [{
					required: true,
					message: '请输入教材名称',
					trigger: 'blur'
				}],
				textbookCover: [{
					required: true,
					message: '请上传封面',
					trigger: 'blur'
				}],
				version: [{
					required: true,
					message: '请上输入版本号',
					trigger: 'blur'
				}],
				state: [{
					required: true,
					message: '请选择状态',
					trigger: 'blur'
				}],
				majorId: [{
					required: true,
					message: '请选择专业',
					trigger: 'blur'
				}],
				prefaceHtml: [{
					required: true,
					message: '请输入前言',
					trigger: 'blur'
				}],
				rank: [{
					validator: checkNumber
				},
				{
					required: true,
					message: '请输入排序号'
				}
				],
				chapterName: [{
					required: true,
					message: '请输入章名称',
					trigger: 'blur'
				}],
				sectionName: [{
					required: true,
					message: '请输入小节名称',
					trigger: 'blur'
				}],
			},
		}
	},
	created() {
		this.getMajorList()
		this.getTreeList()
		this.getDateList()
	},
	methods: {
		contentChangeAi(data, index) {
			this.aiedithtml = data.html;
		},
		editAiCreate() {
			this.aiedithtml = this.aihtml;
			this.adeditshow = true;
		},
		editCloseAiCreate() {
			this.aiedithtml = this.aihtml;
			this.adeditshow = false;
		},
		checkAiCreate() {
			if (!this.aiedithtml) {
				this.$message({
					message: '内容不能为空',
					type: 'error'
				});
				return
			}
			this.addToSection(this.aiedithtml)
			this.adeditshow = false;
			this.aiedithtml = '';
		},
		reStartAiCreate() {
			this.aihtml = '';
			this.rightstate = 2;
			this.startAiCreate()
		},
		addToSectionBefore() {
			if (!this.aihtml) {
				this.$message({
					message: '内容不能为空',
					type: 'error'
				});
				return
			}
			this.addToSection(this.aihtml)
		},
		startAiCreate() {
			if (this.aicreateing) {
				return
			}
			if (!this.aiForm.contentRefer) {
				this.$message({
					message: '请输入内容框架',
					type: 'error'
				});
				return
			}
			if (!this.aiForm.knowledge) {
				this.$message({
					message: '请输入核心知识点',
					type: 'error'
				});
				return
			}
			this.aicreateing = true;
			generateTextbookSectionContent({
				...this.aiForm,
				chapterSectionId: this.openInfo.chapterSectionId
			}).then(res => {
				if (res.code == '200') {
					var contentHtmlBody = document.createElement('html')
					var innerHTMLInfo = res.data || '';
					if (innerHTMLInfo.indexOf('```html') > -1) {
						innerHTMLInfo = innerHTMLInfo.split('```html')[1]
					}
					contentHtmlBody.innerHTML = innerHTMLInfo
					var aihtml = contentHtmlBody.getElementsByTagName('body')[0].innerHTML;
					this.aihtml = aihtml;
					this.rightstate = 1
				} else {
					this.$message({
						message: res.message,
						type: 'error'
					});
				}
			}).finally(() => {
				this.aicreateing = false;
			});
		},
		addToSection(contentHtml) {
			var newData = {
				page: this.openList.length + 1,
				contentHtml: contentHtml,
			}
			this.openList.push(newData)
			this.sectionEdited = true;
			this.closeAIcontent();
			this.aihtml = '';
		},
		openLeft() {
			if (this.rightstate != 1) {
				this.rightstate = 1;
			} else {
				this.rightstate = 2;
			}
		},
		openRight() {
			if (this.rightstate != 3) {
				this.rightstate = 3;
			} else {
				this.rightstate = 2;
			}
		},
		openAIcontent() {
			if (!this.openInfo.chapterSectionId) {
				return
			}
			this.rightstate = 2;
			this.aicreate = true;
		},
		closeAIcontent() {
			this.rightstate = 3;
			this.aiForm.contentRefer = '';
			this.aiForm.knowledge = '';
			this.aicreate = false;
		},
		addDataContent(clear) {
			if (this.loading) {
				return
			}
			this.loading = true;
			var data = {
				textbookId: this.textbookId,
				chapterSectionId: this.openInfo.chapterSectionId,
				contentList: this.openList
			}
			saveBatchTextbookSectionContent(data).then(res => {
				if (res.code == '200') {
					if (clear == 2) {
						this.$message({
							message: res.message,
							type: 'success'
						});
					}
					this.sectionEdited = false;
					this.sectionEditIndex = 0;
					if (clear == 1) {
						this.openInfo.textbookChapterId = '';
						this.openInfo.chapterName = '';
						this.openInfo.pieceName = '';
						this.openInfo.chapterSectionId = '';
						this.openInfo.sectionName = '';
						this.openInfo.beforeSectionId = '';
						this.openList = [];
						if (this.timer) {
							clearInterval(this.timer);
							this.timer = null;
						}
					}
					this.getTreeList();
				} else {
					this.$message({
						message: res.message,
						type: 'error'
					});
				}
				this.loading = false;
			}).catch(err => {
				this.loading = false;
			}).finally(() => {
				this.loading = false;
				this.sectionEditIndex = 0;
				this.sectionEdited = false;
				this.closeAIcontent();
			})
		},
		openDeleteContent(page, index) {
			this.sectionEdited = true;
			this.openList.map(item => {
				if (item.page >= page) {
					item.page = item.page - 1
				}
			})
			this.openList.splice(index, 1);
		},
		openAddContent(page, index) {
			this.sectionEdited = true;
			var newData = {
				page: page,
				contentHtml: '',
				sectionContentId: new Date().getTime()
			}
			this.openList.map(item => {
				if (item.page >= page) {
					item.page = item.page + 1
				}
			})
			this.openList.splice(index, 0, newData)
		},
		contentChange(data, index) {
			if (this.sectionEditIndex < 2) {
				this.sectionEditIndex++
			} else {
				this.sectionEdited = true;
				this.openList[index].contentHtml = data.html;
			}
		},
		openClear() {
			this.adeditshow = false;
			this.aicreate = false;
			this.rightstate = 3;
			this.aiedithtml = '';
			this.aihtml = '';
		},
		openInfoSection(chapter, section) {
			if (this.aicreateing) {
				this.$alert('正在生成AI内容，请稍后！', '提示', {
					type: 'warning'
				})
				return
			}
			if (this.sectionEdited) {
				this.$alert('您还有小节未保存，请保存后再进行此操作！', '提示', {
					type: 'warning'
				})
				return
			}
			this.openList = [];
			this.openInfo.textbookChapterId = chapter.textbookChapterId;
			this.openInfo.chapterName = chapter.chapterName;
			this.openInfo.pieceName = chapter.pieceName;
			this.openInfo.chapterSectionId = section.chapterSectionId;
			this.openInfo.sectionName = section.sectionName;
			this.sectionEditIndex = 0;
			this.openClear();
			var beforeIndex = this.sectionIds.indexOf(section.chapterSectionId);
			if (beforeIndex > 0) {
				this.openInfo.beforeSectionId = this.sectionIds[beforeIndex - 1];
			} else {
				this.openInfo.beforeSectionId = ""
			}
			selectTextbookContentList({
				chapterSectionId: section.chapterSectionId
			}).then(res => {
				this.openList = res.data || [];
				if (this.openList.length == 0) { //获取上一节最后一页
					if (this.openInfo.beforeSectionId) {
						selectTextbookContentList({
							chapterSectionId: this.openInfo.beforeSectionId
						}).then(res => {
							var lastList = res.data || [];
							if (lastList && lastList.length > 0) {
								this.newPage = lastList[lastList.length - 1].page * 1 + 1;
							} else {
								this.newPage = 1
							}
						})
					} else {
						this.newPage = 1
					}
				} else {
					this.newPage = this.openList[0].page * 1
				}
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
				this.timer = setInterval(() => {
					this.addDataContent(0)
				}, 60000)
			})
		},
		openAddSection(chapter) { //节管理
			this.sectionAddForm.textbookChapterId = chapter.textbookChapterId
			this.sectionAddDialog = true;
		},
		addDataSection() {
			this.dataloading = true;
			setTimeout(_ => {
				this.dataloading = false;
			}, 1000)
			this.$refs.sectionAddForm.validate((valid) => {
				if (valid) {
					var data = Object.assign({}, this.sectionAddForm, {
						textbookId: this.textbookId
					});
					saveTextbookChapterSection(data).then(async res => {
						if (res.code == '200') {
							this.$message({
								message: res.message,
								type: 'success'
							});
							this.getTreeList();
							this.resetAddSection();
						} else {
							this.$message({
								message: res.message,
								type: 'error'
							});
						}
					});
				}
			})
		},
		resetAddSection() {
			this.sectionAddDialog = false;
			this.$refs.sectionAddForm.resetFields();
			this.$refs.sectionAddForm.clearValidate();
		},
		openEditSection(section) {
			this.sectionEditForm = Object.assign({}, section)
			this.sectionEditDialog = true;
		},
		editDataSection() {
			this.dataloading = true;
			setTimeout(_ => {
				this.dataloading = false;
			}, 1000)
			this.$refs.sectionEditForm.validate((valid) => {
				if (valid) {
					var data = Object.assign({}, this.sectionEditForm, {
						textbookId: this.textbookId
					});
					updateTextbookChapterSection(data).then(async res => {
						if (res.code == '200') {
							this.$message({
								message: res.message,
								type: 'success'
							});
							this.getTreeList();
							this.resetEditSection();
						} else {
							this.$message({
								message: res.message,
								type: 'error'
							});
						}
					});
				}
			})
		},
		resetEditSection() {
			this.sectionEditDialog = false;
			this.$refs.sectionEditForm.resetFields();
			this.$refs.sectionEditForm.clearValidate();
		},
		openDeleteSection(section) {
			if (this.sectionEdited) {
				this.$alert('您还有小节未保存，请保存后再进行此操作！', '提示', {
					type: 'warning'
				})
				return
			}
			this.$confirm('确认删除此小节?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				removeTextbookChapterSection({
					chapterSectionId: section.chapterSectionId
				}).then(async res => {
					if (res.code == '200') {
						this.$message({
							message: res.message,
							type: 'success'
						})
						this.getTreeList();
					} else {
						this.$message({
							message: res.message,
							type: 'error'
						})
					}
				})
			}).catch(() => { });

		},
		openAddChapter() { //章管理
			this.chapterAddDialog = true;
		},
		addDataChapter() {
			this.dataloading = true;
			setTimeout(_ => {
				this.dataloading = false;
			}, 1000)
			this.$refs.chapterAddForm.validate((valid) => {
				if (valid) {
					var data = Object.assign({}, this.chapterAddForm, {
						textbookId: this.textbookId
					});
					saveTextbookChapter(data).then(async res => {
						if (res.code == '200') {
							this.$message({
								message: res.message,
								type: 'success'
							});
							this.getTreeList();
							this.resetAddChapter();
						} else {
							this.$message({
								message: res.message,
								type: 'error'
							});
						}
					});
				}
			})
		},
		resetAddChapter() {
			this.chapterAddDialog = false;
			this.$refs.chapterAddForm.resetFields();
			this.$refs.chapterAddForm.clearValidate();
		},
		openEditChapter(chapter) {
			this.chapterEditForm = Object.assign({}, chapter)
			this.chapterEditDialog = true;
		},
		editDataChapter() {
			this.dataloading = true;
			setTimeout(_ => {
				this.dataloading = false;
			}, 1000)
			this.$refs.chapterEditForm.validate((valid) => {
				if (valid) {
					var data = Object.assign({}, this.chapterEditForm, {
						textbookId: this.textbookId
					});
					updateTextbookChapter(data).then(async res => {
						if (res.code == '200') {
							this.$message({
								message: res.message,
								type: 'success'
							});
							this.getTreeList();
							this.resetEditChapter();
						} else {
							this.$message({
								message: res.message,
								type: 'error'
							});
						}
					});
				}
			})
		},
		resetEditChapter() {
			this.chapterEditDialog = false;
			this.$refs.chapterEditForm.resetFields();
			this.$refs.chapterEditForm.clearValidate();
		},
		openDeleteChapter(chapter) {
			if (this.sectionEdited) {
				this.$alert('您还有小节未保存，请保存后再进行此操作！', '提示', {
					type: 'warning'
				})
				return
			}
			this.$confirm('确认删除此章?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				removeTextbookChapter({
					textbookChapterId: chapter.textbookChapterId
				}).then(async res => {
					if (res.code == '200') {
						this.$message({
							message: res.message,
							type: 'success'
						})
						this.getTreeList();
					} else {
						this.$message({
							message: res.message,
							type: 'error'
						})
					}
				})
			}).catch(() => { });
		},
		changeOpen(chapter) {
			if (this.openChapters.includes(chapter.textbookChapterId)) {
				var sliceIndex = this.openChapters.indexOf(chapter.textbookChapterId);
				this.openChapters.splice(sliceIndex, 1)
			} else {
				this.openChapters.push(chapter.textbookChapterId)
			}
		},
		editData() { //教材编辑
			if (this.sectionEdited) {
				this.$alert('您还有小节未保存，请保存后再进行此操作！', '提示', {
					type: 'warning'
				})
				return
			}
			this.$refs.editForm.validate((valid) => {
				if (valid) {
					var data = Object.assign({}, this.editForm);
					updateTextbook(data).then(async res => {
						if (res.code == '200') {
							this.$message({
								message: res.message,
								type: 'success'
							})
							this.closeCheck();
						} else {
							this.$message({
								message: res.message,
								type: 'error'
							})
						}
					})
				}
			})
		},
		getMajorList() {
			majorList({}).then(res => {
				this.majors = res.data || []
			})
		},
		getTreeList() {
			if (this.from == 'admin') {
				selectTextbookDirectory({
					textbookId: this.textbookId,
					chapterName: this.chapterName,
				}).then(async result => {
					this.treeList = result.data.chapterDirectoryDtos || [];
					this.getSectionIds()
				});
			} else {
				selectTextbookDirectoryByUserId({
					textbookId: this.textbookId,
					chapterName: this.chapterName,
				}).then(async result => {
					this.treeList = result.data.chapterDirectoryDtos || [];
					this.getSectionIds()
				});
			}
			selectTextbookChapterCount({
				textbookId: this.textbookId,
			}).then(async res => {
				this.treeNum = res.data || 0;
			});
		},
		getSectionIds() {
			selectTextbookDirectory({//为了获取全部的小节ids 防止查询后页码错乱
				textbookId: this.textbookId,
			}).then(async res => {
				var sectionIds = [];
				var mapList = res.data.chapterDirectoryDtos || []
				mapList.map(chepter => {
					if (chepter.sectionDirectoryDtos && chepter.sectionDirectoryDtos.length > 0) {
						chepter.sectionDirectoryDtos.map(section => {
							if (section.maxPage && section.maxPage > 0) {
								sectionIds.push(section.chapterSectionId)
							}
						})
					}
				})
				this.sectionIds = sectionIds;
			});
		},
		getDateList() {
			selectTextbookDetail({
				textbookId: this.textbookId
			}).then(async res => {
				this.editForm = Object.assign({}, res.data);
			});
		},
		toInfo() {
			this.$router.push({
				name: 'textbookInfo',
				query: {
					textbookId: this.textbookId
				}
			})
		},
		closeCheck() {
			var view = this.$route;
			this.$store.dispatch('tagsView/delView', view).then(({
				visitedViews
			}) => {
				if (this.isActive(view)) {
					this.toLastView(visitedViews, view)
				}
			})
		},
		isActive(route) {
			return route.path === this.$route.path
		},
		toLastView(visitedViews, view) {
			const latestView = visitedViews.slice(-1)[0]
			if (latestView) {
				this.$router.push(latestView)
			} else {
				if (view.name === 'Dashboard') {
					this.$router.replace({
						path: '/redirect' + view.fullPath
					})
				} else {
					this.$router.push('/')
				}
			}
		},
	},
	beforeRouteLeave(to, from, next) {
		if (this.sectionEdited) {
			this.$alert('您还有小节未保存，请保存后再进行此操作！', '提示', {
				type: 'warning'
			})
			next(false);
		} else {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
			next();
		}
	},
}
</script>